1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <cstdio> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; const int maxn = 1e5 + 5; struct E{ int to, nxt; }e[maxn << 1]; int head[maxn], tot = 0; void addedge(int u, int v){ e[++tot].to = v, e[tot].nxt = head[u]; head[u] = tot; } int s[maxn], dep[maxn], f[maxn]; int cu, cv; void dfs(int cur, int fa){ dep[cur] = dep[fa] + 1; f[cur] = fa; if (dep[cur] & 1) s[cur] = 1; else s[cur] = -1; for (int i = head[cur]; i; i = e[i].nxt){ int v = e[i].to; if (v != fa){ if (dep[v]){ if (cu == 0) cu = cur, cv = v; } else dfs(v, cur), s[cur] += s[v]; } } } int n, m; int abs(int x){return x < 0 ? -x : x;} void work1(){ if (s[1] != 0){puts("-1"); exit(0);} int ans = 0; for (int i = 1; i <= n; i++) ans += abs(s[i]); printf("%d\n", ans); exit(0); } void work2(){ if (s[1] % 2 != 0){puts("-1"); exit(0);} int t = -s[1] / 2; int ans = abs(t); for (; cu; cu = f[cu]) s[cu] += t; for (; cv; cv = f[cv]) s[cv] += t; for (int i = 1; i <= n; i++) ans += abs(s[i]); printf("%d\n", ans); exit(0); } vector <int> v; void work3(){ if (s[1] != 0){puts("-1"); exit(0);} for (; cu != cv; cu = f[cu]) dep[cu] = 0, v.push_back(s[cu]); sort(v.begin(), v.end()); int mid = v[(v.size() - 1) / 2]; int ans = abs(mid); for (int i = 1; i <= n; i++) if (dep[i] != 0) ans += abs(s[i]); else ans += abs(s[i] - mid); printf("%d\n", ans); exit(0); } int main(){ scanf("%d%d", &n, &m); for (int u, v, i = 1; i <= m; i++){ scanf("%d%d", &u, &v); addedge(u, v); addedge(v, u); } dfs(1, 0); if (m == n - 1) work1(); if ((dep[cu] - dep[cv]) % 2 == 0) work2(); work3(); return 0; }
|